package org.opsli.modulars.business.app.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.opsli.api.wrapper.system.user.UserModel;
import org.opsli.common.annotation.ApiRestController;
import org.opsli.common.api.Result;
import org.opsli.core.utils.JwtUtil;
import org.opsli.core.utils.UserUtil;
import org.opsli.modulars.business.appVersion.entity.AppVersion;
import org.opsli.modulars.business.appVersion.entity.AppWorkVersion;
import org.opsli.modulars.business.appVersion.service.IAppVersionService;
import org.opsli.modulars.business.emergency.entity.EmergencyReport;
import org.opsli.modulars.business.gasWorkTask.entity.GasWorkTask;
import org.opsli.modulars.business.gasWorkTask.entity.GasWorkTaskData;
import org.opsli.modulars.business.gasWorkTask.service.IGasWorkTaskService;
import org.opsli.modulars.business.gasWorkTask.web.GasWorkTaskRestController;
import org.opsli.modulars.business.gasWorkTaskRecord.web.GasWorkTaskRecordRestController;
import org.opsli.modulars.business.projectTask.entity.ProjectTaskData;
import org.opsli.modulars.business.projectTaskRecord.entity.ProjectTaskRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Api(tags="app所需接口三类")
@Slf4j
@ApiRestController("/appbusiness/three")
public class AppThreeController {

    @Autowired
    private IGasWorkTaskService iGasWorkTaskService;
    @Autowired
    private GasWorkTaskRestController gasWorkTaskRestController;
    @Autowired
    private IAppVersionService iAppVersionService;
    @Autowired
    private GasWorkTaskRecordRestController gwtrrController;

    /**
     * @功能：显示该用户下所分配的任务
     * @return
     */
    @GetMapping(value = "/gasWorkTaskList")
    public Result<IPage<GasWorkTaskData>> gasWorkTaskList(HttpServletRequest request,
                                                          @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                          @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                          @RequestParam(name="keyword") String keyword) throws Exception{

        String username = JwtUtil.getUserNameByToken(request);
        UserModel user = UserUtil.getAppUser(username);
        GasWorkTaskData taskData=new GasWorkTaskData();
        taskData.setDevid(user.getCompanyId());
        if(user.getIsOutworker().equals("1")) {
            taskData.setUserId(user.getId());
        }
        taskData.setWorkUserName(keyword);
        taskData.setWorkState("0"); //工单状态 0 待办 1未完成 2已完成
        Result<IPage<GasWorkTaskData>> result = new Result<IPage<GasWorkTaskData>>();
        Page<GasWorkTaskData> pageList = new Page<GasWorkTaskData>(pageNo,pageSize);

        pageList = iGasWorkTaskService.getGasWorkTaskList(pageList, taskData,(pageNo-1)*pageSize,pageSize);
        result.setResult(pageList);
        result.setSuccess(true);
        return result;
    }

    /**
     * @功能:显示系统下发的未完成任务
     * @return
     */
    @GetMapping(value = "/gasWorkCommonList")
    public Result<IPage<GasWorkTaskData>> gasWorkCommonList(HttpServletRequest request,
                                                          @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                          @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                          @RequestParam(name="keyword") String keyword) throws Exception{

        String username = JwtUtil.getUserNameByToken(request);
        UserModel user = UserUtil.getAppUser(username);
        GasWorkTaskData taskData=new GasWorkTaskData();
        taskData.setDevid(user.getCompanyId());
//        if(user.getIsOutworker().equals("1")) {
//            taskData.setUserId(user.getId());
//        }
        taskData.setWorkUserName(keyword);
        taskData.setWorkState("1"); //工单状态 0 待办 1未完成 2已完成
        Result<IPage<GasWorkTaskData>> result = new Result<IPage<GasWorkTaskData>>();
        Page<GasWorkTaskData> pageList = new Page<GasWorkTaskData>(pageNo,pageSize);

        pageList = iGasWorkTaskService.getGasWorkCommonList(pageList, taskData,(pageNo-1)*pageSize,pageSize);
        result.setResult(pageList);
        result.setSuccess(true);
        return result;
    }

    /**
     * @功能：获取应急事件
     * @return
     */
    @GetMapping(value = "/gasWorkCheckList")
    public Result<IPage<GasWorkTaskData>> gasWorkCheckList(HttpServletRequest request, GasWorkTaskData record,
                                                          @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                          @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                           @RequestParam(name="msgCategory", defaultValue="0") String msgCategory) throws Exception{

        String username = JwtUtil.getUserNameByToken(request);
        UserModel user = UserUtil.getAppUser(username);
        record.setDevid(user.getCompanyId());
        if(user.getIsOutworker().equals("1")) {
            record.setUserId(user.getId());
        }
        record.setWorkState(msgCategory);
        Result<IPage<GasWorkTaskData>> result = new Result<IPage<GasWorkTaskData>>();
        Page<GasWorkTaskData> pageList = new Page<GasWorkTaskData>(pageNo,pageSize);

        pageList = iGasWorkTaskService.gasWorkCheckList(pageList, record,(pageNo-1)*pageSize,pageSize);
        result.setResult(pageList);
        result.setSuccess(true);
        return result;
    }

    /** 任务提交
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/gasWorkTaskAdd", method = RequestMethod.PUT)
    @Transactional(readOnly = false)
    public Result<GasWorkTaskData> gasWorkTaskAdd(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        Result<GasWorkTaskData> result = new Result<GasWorkTaskData>();
        try {
            String username = JwtUtil.getUserNameByToken(request);
            UserModel user = UserUtil.getAppUser(username);

            /** 进度上传时间 */
            Date date = new Date();
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String str = format.format(date);

            String id=jsonObject.getString("id"); //任务id
            String workState=jsonObject.getString("workState"); //工单状态 0 待办 1未完成 2已完成
            String workPic=jsonObject.getString("workPic"); //图片
            String comment=jsonObject.getString("comment"); //备注
            String reason=jsonObject.getString("reason"); //未完成原因

            GasWorkTaskData gaswt=new GasWorkTaskData();
            gaswt.setFinishTime(str); //任务完成时间
            gaswt.setId(id);
            gaswt.setWorkState(workState);
            gaswt.setWorkPic(workPic);
            gaswt.setComment(comment);
            gaswt.setReason(reason);

            gasWorkTaskRestController.gasTaskAdd(gaswt);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败!");
        }
        return result;
    }


    /** 领取公共任务
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/gasWorkCommonGet", method = RequestMethod.PUT)
    @Transactional(readOnly = false)
    public Result<GasWorkTaskData> gasWorkCommonGet(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        Result<GasWorkTaskData> result = new Result<GasWorkTaskData>();
        try {
            String username = JwtUtil.getUserNameByToken(request);
            UserModel user = UserUtil.getAppUser(username);

            String id=jsonObject.getString("id"); //任务id

            //把原数据放到 工单记录表中
            iGasWorkTaskService.getTaskReold(id,user.getId());

            //往更新表里 更新当前领取人的信息
            GasWorkTaskData gaswt=new GasWorkTaskData();
            gaswt.setId(id);
            gaswt.setUserId(user.getId());
            gaswt.setUserName(user.getRealName());
            gaswt.setWorkState("0");
            gasWorkTaskRestController.gasCommonGet(gaswt);

            //清空原数据
            iGasWorkTaskService.getUpdateId(gaswt.getId());
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败!");
        }
        return result;
    }

    /** 判断当前任务是否已被领取
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "/gasWorkCommonGetWhether", method = RequestMethod.PUT)
    @Transactional(readOnly = false)
    public Result<GasWorkTaskData> gasWorkCommonGetWhether(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        Result<GasWorkTaskData> result = new Result<GasWorkTaskData>();
        try {

            String id=jsonObject.getString("id"); //任务id是


            GasWorkTaskData gasWorkTaskData = iGasWorkTaskService.getByTaskId(id);

            if(null != gasWorkTaskData){
                //当工单状态为  0 待办 2 已完成时 不可领取
                if(gasWorkTaskData.getWorkState().equals("0") || gasWorkTaskData.getWorkState().equals("2")){
                    result.setSuccess(false);
                }else {
                    result.setSuccess(true);
                }
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败!");
        }
        return result;
    }


    @GetMapping(value = "/upgradeWork")
    public Result<Map> upgradeWork(HttpServletRequest request, @RequestParam(name="appid") String appid, @RequestParam(name="version") String version, @RequestParam(name="imei") String imei) throws Exception{

        System.out.println("appid="+appid+",version="+version+",imei="+imei);
        Result<Map> result=new Result<Map>();
        AppWorkVersion appVersion=iAppVersionService.findLastWork();
        Map map=new HashMap();
        map.put("version",appVersion.getAppVersion());
        map.put("note",appVersion.getNote());
        map.put("url",appVersion.getUrl());
        result.setSuccess(true);
        result.setResult(map);
        return result;
    }
}
